package org.richin.io.util;

import java.nio.ByteBuffer;

public class ByteAccumulator {
	 public static final int DEFAULT_BUFFER_SIZE = 1024;
	    private ByteBuffer buffer;


	    public ByteAccumulator(final ByteBuffer buffer) {
	        this.buffer = buffer;
	    }


	    public ByteAccumulator() {
	        this(DEFAULT_BUFFER_SIZE);
	    }


	    public ByteAccumulator(final int size) {
	        this(ByteBuffer.allocate(size));
	    }


	    public void append(ByteBuffer buf) {
	        if (buf == null) {
	            return;
	        }
	        if (buffer.remaining() < buf.remaining()) {
	            final int position = buffer.position();
	            buffer.flip();
	            final int newCap = (int) Math
	                    .round((buffer.remaining() + buf.remaining()) * 2);

	            final ByteBuffer newBuffer = buffer.isDirect() ? ByteBuffer
	                    .allocateDirect(newCap) : ByteBuffer.allocate(newCap);
	            newBuffer.put(buffer);
	            buffer = newBuffer;
	            buffer.position(position);
	        }
	        assert buffer.remaining() < buf.remaining();
	        buffer.put(buf);
	    }


	    public ByteBuffer get() {
	        return buffer.duplicate();
	    }
}
